﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICSharpCode.TextEditor.Document;

namespace tiDE.CodeFolding
{
    public class z80Folding : IFoldingStrategy
    {
        public List<FoldMarker> GenerateFoldMarkers(IDocument document, string fileName, object parseInformation)
        {
            List<FoldMarker> foldMarkers = new List<FoldMarker>();
            string[] Lines = document.TextContent.Replace("\r", "").Split('\n');
            int lineNumber = 0, lastLineLength = 0;
            string lastLabelText = "";
            int lastLabel = -1;
            int linesOfWhitespace = 0,
                lineNonWhitespace = 0;
            if (Lines.Length == 1)
                return foldMarkers;
            foreach (string Line in Lines)
            {
                string line = Line.Trim();
                line = Assembler.StripComments(line).Trim();
                if (Assembler.LabelRegex.IsMatch(line)) // Label
                {
                    if (lastLabel != -1)
                    {
                        if (lineNonWhitespace != 0)
                            foldMarkers.Add(new FoldMarker(document, lastLabel, lastLabelText.Length, lineNumber - 1 - linesOfWhitespace, lastLineLength));
                        lastLabel = -1;
                    }
                    lastLabel = lineNumber;
                    lastLabelText = Line;
                    lineNonWhitespace = -1;
                }
                if (string.IsNullOrEmpty(line))
                    linesOfWhitespace++;
                else
                {
                    linesOfWhitespace = 0;
                    lastLineLength = Line.Length;
                    lineNonWhitespace++;
                }
                lineNumber++;
            }
            if (lastLabel != -1)
            {
                foldMarkers.Add(new FoldMarker(document, lastLabel, lastLabelText.Length, lineNumber - 1, lastLineLength));
                lastLabel = -1;
            }
            return foldMarkers;
        }
    }
}
